package com.example.juccode.sync.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * author: 刘中魁
 */
public class LSaleTicker {
    public static void main(String[] args) {
        //创建资源类
        Ticket ticket = new Ticket();
        int num = 40;
        //创建三个线程
        new Thread(() -> {
           for (int i = 0; i < num; i++){
               ticket.sale();
           }
        }, "A1").start();

        new Thread(() -> {
            for (int i = 0; i < num; i++){
                ticket.sale();
            }
        }, "B1").start();

        new Thread(() -> {
            for (int i = 0; i < num; i++){
                ticket.sale();
            }
        }, "C1").start();

    }
}
class Ticket {
    //票数
    private int number = 30;
    //创建可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    public void sale() {
        //上锁
        lock.lock();
        //判断是否有票
        try {
            if (number > 0) {
                number--;
                System.out.println(Thread.currentThread().getName() + "卖出1张张票，剩余" + number + "张票");
            }
        }finally {
            //解锁
            lock.unlock();
        }


    }
}
